//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.service;

import cn.hutool.core.date.DateUnit;
import com.github.pagehelper.PageHelper;
import com.wsd.smartcarwasher.dao.CardOrderDao;
import com.wsd.smartcarwasher.dao.MachineDao;
import com.wsd.smartcarwasher.dao.OrderDao;
import com.wsd.smartcarwasher.dao.UserInfoDao;
import com.wsd.smartcarwasher.domain.*;
import com.wsd.smartcarwasher.util.DateUtil;
import com.wsd.smartcarwasher.util.PageInfo;
import com.wsd.smartcarwasher.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrderService {
    private static final Logger logger = LoggerFactory.getLogger(OrderService.class);
    @Resource
    private OrderDao orderDao;
    @Resource
    private UserCouponService userCouponService;

    @Resource
    private UserInfoDao UserInfoDao;
    @Resource
    @Lazy
    private MachineService machineService;
    @Resource
    private MachineDao machineDao;
    @Resource
    private CardOrderDao cardOrderDao;
    @Resource
    @Lazy
    private SavaScalingService savaScalingService;


    public OrderService() {
    }

    public int updatePayNode(String orderSn,Integer days)
    {
        Order order=this.orderDao.queryOrderInfoByOrderSn(orderSn);
       return this.orderDao.updatePayNode(orderSn,days);
    }

    public OrderInfo queryOrderInfoByOrderSn(String orderSn) {
        return this.orderDao.queryOrderInfoByOrderSn(orderSn);
    }
    public OrderInfo queryOrderByOrderSn(String orderSn) {
        return this.orderDao.queryOrderByOrderSn(orderSn);
    }

    public String queryByLatelyUserId(String orderSn)
    {
        String time=null;
        try{
            OrderInfo order = this.queryOrderInfoByOrderSn(orderSn);
            Map<String,Object> map=this.orderDao.queryByLatelyUserId(order.getUserId());
            if(StringUtil.isNullOrEmpty(map))
            {
                return null;
            }
            time=map.get("time").toString();
            return time;
        }catch (Exception e)
        {
            logger.info("订单最后一次消费记录插入失败");
        }
       return null;
    }
    public List<OrderInfo> queryAllOrderList()
    {
       return this.queryAllOrderList();
    }

    public  int updateServiceStatus(OrderInfo orderInfo)
    {
        orderInfo.setServiceStatus(1);
        return  this.orderDao.updateOrderInfo(orderInfo);
    }
    OrderInfo queryUnPaidOrder(String userId) {
        return this.orderDao.queryUnPaidOrder(userId);
    }

    //查询未结束的订单
    public List<OrderInfo> queryUnEndTimeOrder()
    {
        return  this.orderDao.queryUnEndTimeOrder();
    }
    //巡检未结束的订单
    public int createUnEndTimeOrder(String orderSn)
    {
        return  this.orderDao.createUnEndTimeOrder(orderSn);
    }

//
//    public int orderScheduled(String orderSn)
//    {
//
//        OrderInfo orderInfo=this.orderDao.queryOrderInfoByOrderSn(orderSn);
//        if(orderInfo.getStartTime().getTime()-new Date().getTime()>600000)
//        {
//            orderInfo.setEndTime(new Date());
//            this.orderDao.updateOrderInfo(orderInfo);
//            return 1;
//        }
//        return 0;
//    }

    @Transactional
    public int createOrder(OrderInfo order) {
        order.setOrderStatus(100);
        order.setPayStatus(0);
        order.setOrderSn(this.generateOrderSn());
        order.setCreateTime(DateUtil.getSysTime());
        BigDecimal price=this.calculatePayPrice(order);

        if(price.compareTo(BigDecimal.ZERO)<0)
        {
            price=BigDecimal.ZERO;
        }
        order.setPayPrice(price);
        Machine machine = machineDao.queryMachineById(order.getMachineId());
        if(machine.getPartnerId()!=null){//添加商户信息
            order.setProrateStatus(1);
            order.setPartnerId(machine.getPartnerId());
        }else{
            order.setProrateStatus(0);
        }
        int changeRow = this.orderDao.addOrderInfo(order);
        if (StringUtils.isNotBlank(order.getUserCouponId())) {
            int usedCoupon = this.userCouponService.useUserCoupon(DateUtil.getSysTime(), order.getUserCouponId());
            if (usedCoupon == 0) {
                logger.error("使用优惠券失败：订单id为-" + order.getOrderSn() + "优惠券id为" + order.getUserCouponId());
            }
        }

        return changeRow;
    }

    /**
     * 线上订单数
     * @param orderInfo
     * @return
     */
//    public  Map<String, Object> onlineOrdercount(String sTime, String dTime,Integer serviceId,String partnerId)
//    {
//       return this.orderDao.queryOnline(sTime,dTime,serviceId,partnerId);
//    }
    private BigDecimal calculatePayPrice(OrderInfo orderInfo) {
        if (2 == orderInfo.getPayWayCode()) {
            return new BigDecimal(0.0D);
        } else {
            if (1 == orderInfo.getPayWayCode() && StringUtils.isNotBlank(orderInfo.getUserCouponId())) {
                UserCoupon userCoupon = this.userCouponService.selectUserCoupon(orderInfo.getUserCouponId());
                if (userCoupon != null && userCoupon.getCoupon() != null) {
                    Coupon coupon = userCoupon.getCoupon();
                    if (1 == coupon.getType()) {
                        return orderInfo.getOrderPrice().subtract(coupon.getCouponPrice());
                    }

                    if (2 == coupon.getType()) {
                        return orderInfo.getOrderPrice().multiply(coupon.getCouponRate());
                    }
                }
            }

            return orderInfo.getOrderPrice();
        }
    }

    /**
     * 给订单插入订单金额
     * @param orderInfo
     */
    public void completeOrderCardByPayPrice(OrderInfo orderInfo)
    {
        this.orderDao.updateOrderPayPrice(orderInfo.getOrderSn(),orderInfo.getPayPrice());
    }



    public void payFinishOrder(OrderInfo orderInfo) {
        orderInfo=this.orderDao.queryOrderInfoByOrderSn(orderInfo.getOrderSn());
//        Card card=this.cardService.queryCardInfo(orderInfo.getCardId());
//        if(card.getType()==2)
//        {
//            orderInfo.setPayPrice(orderInfo.getOrderPrice().multiply(card.getCardRate()));
//            System.out.println("orderInfo.setPayPrice为:"+orderInfo.getPayPrice());
//            //8.14改动记录
//            System.out.println("8.14改动记录");
//        }
        orderInfo.setPayStatus(2);
        orderInfo.setPayTime(DateUtil.getSysTime());
        this.updateOrder(orderInfo);
        //更新洗车省时省水比例
//        记录省时省水比例
        this.savaScalingService.createSavaScaling(orderInfo.getOrderSn());
        //查看优惠卷
        orderInfo =this.orderDao.queryOrderInfoByOrderSn(orderInfo.getOrderSn());
        if(StringUtils.isNotBlank(orderInfo.getUserCouponId())){
            UserCoupon userCoupon  = userCouponService.getUserCouponById(orderInfo.getUserCouponId());
            UserInfo userInfo=UserInfoDao.findByUserId(userCoupon.getUserId());
            if(StringUtils.isNotBlank(userInfo.getFromId())){
                userCouponService.activationUserCoupon(userInfo.getFromId(),userCoupon.getCouponId());
            }
        }
        //回调机器
        this.machineService.startMachine(orderInfo.getOrderSn(),orderInfo.getMachineId().toString());
    }

    int updateOrder(OrderInfo order) {
        return this.orderDao.updateOrderInfo(order);
    }

    private String generateOrderSn() {
        String orderSn = StringUtil.getOrderSn();

        for(List orderSns = this.getAllOrderSn(); orderSns.contains(orderSn); orderSn = StringUtil.getOrderSn()) {
        }

        return orderSn;
    }

    private List<String> getAllOrderSn() {
        List<String> orderSns = this.orderDao.getAllOrderSn();
        if (orderSns == null) {
            orderSns = Collections.emptyList();
        }

        return orderSns;
    }

    public int deleteOrder(OrderInfo order) {
        if (StringUtils.isNotBlank(order.getUserCouponId()) && order.getConsumed()==0) {
            int rollBackRows = this.userCouponService.rollBackUserCoupon(order.getUserCouponId());
            if (rollBackRows == 0) {
                return 0;
            }
        }
        return this.orderDao.deleteOrderInfo(order.getOrderSn());
    }



    public int deleteOrderLyj(OrderInfo order) {
        return this.orderDao.deleteOrderInfo(order.getOrderSn());
    }

    public PageInfo<OrderInfo> queryAllOrdersByCondition(Map<String,Object> filterCondition) {
//        filterCondition.put("cardId",Integer.parseInt(filterCondition.get("cardId").toString()));
        PageHelper.startPage(Integer.valueOf(filterCondition.get("Page").toString()),Integer.valueOf(filterCondition.get("PageSize").toString()));
        List<OrderInfo> lor =  orderDao.queryAllOrdersByCondition(filterCondition);
       return new PageInfo<>(lor);
    }

    public int finishOrder(String orderSn) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderSn(orderSn);
        orderInfo.setConsumed(4);
        orderInfo.setEndTime(new Date());
        return this.updateOrder(orderInfo);
    }

    public int refundOrder(String orderSn,String partner_trade_no) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderSn(orderSn);
        orderInfo.setProrateStatus(4);
        orderInfo.setEndTime(new Date());
        orderInfo.setProrateSn(partner_trade_no);
        return this.updateOrder(orderInfo);
    }
    //改变会员卡退款的会员卡购买订单状态
    public int refundCardOrder(String orderSn) {
        CardOrder orderInfo = new CardOrder();
        orderInfo.setOrderSn(orderSn);
        orderInfo.setIsRefund(1);
        return this.cardOrderDao.updateCardOrder(orderInfo);
    }

    public int saveOrderCarWashPhoto(OrderInfo orderInfo) {
        return this.orderDao.saveOrderCarWashPhoto(orderInfo);
    }

    public boolean queryCardIsActivityAndUsed(String userId,String ucId) {

        if(StringUtil.isNullOrEmpty(this.orderDao.queryCardIsActivityAndUsed(userId,ucId)))
        {
            return false;
        }
        return true;
    }

    public boolean queryCreatedOrder(String userId) {
        OrderInfo orderInfo=this.orderDao.queryCreatedOrder(userId);
        if(StringUtil.isNullOrEmpty(orderInfo))
        {
            return false;
        }
        if(!StringUtil.isNullOrEmpty(orderInfo.getPayTime()))
        {

            if(cn.hutool.core.date.DateUtil.between(orderInfo.getPayTime(),new Date(), DateUnit.SECOND)<=45)
            {
                return true;
            }
        }

            return false;
    }
}

/*
package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.dao.OrderDao;
import com.wsd.smartcarwasher.domain.Coupon;
import com.wsd.smartcarwasher.domain.OrderInfo;
import com.wsd.smartcarwasher.domain.UserCoupon;
import com.wsd.smartcarwasher.util.DateUtil;
import com.wsd.smartcarwasher.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;

@Service
public class OrderService {
    private static final Logger logger = LoggerFactory.getLogger(OrderService.class);

    @Resource
    private OrderDao orderDao;

    @Resource
    private UserCouponService userCouponService;

    public OrderInfo queryOrderInfoByOrderSn(String orderSn) {
        return orderDao.queryOrderInfoByOrderSn(orderSn);
    }

    OrderInfo queryUnPaidOrder(String userId) {
        return orderDao.queryUnPaidOrder(userId);
    }

    @Transactional
    public int createOrder(OrderInfo order) {
        order.setOrderStatus(Global.ORDER_STATUS_NORMAL);
        order.setPayStatus(Global.ORDER_PAY_STATUS_UNPAID);
        order.setOrderSn(generateOrderSn());
        order.setCreateTime(DateUtil.getSysTime());
        order.setPayPrice(calculatePayPrice(order));
        int changeRow = orderDao.addOrderInfo(order);
        if (StringUtils.isNotBlank(order.getUserCouponId())) {
            int usedCoupon = userCouponService.useUserCoupon(order.getCreateTime(), order.getUserCouponId());
            if (usedCoupon == 0) {
                logger.error("使用优惠券失败：订单id为-" + order.getOrderSn() + "优惠券id为" + order.getUserCouponId());
            }
        }
        return changeRow;
    }

    // 计算订单实付价格
    private BigDecimal calculatePayPrice(OrderInfo orderInfo) {
        if (Global.PAY_WAY_CODE_CARD == orderInfo.getPayWayCode()) {
            //会员卡支付，实付价格为0
            return new BigDecimal(0.00f);
        } else if (Global.PAY_WAY_CODE_WEI_XIN == orderInfo.getPayWayCode()) {
            //微信支付，实付价格为优惠后价格
            if (StringUtils.isNotBlank(orderInfo.getUserCouponId())) {
                UserCoupon userCoupon = userCouponService.selectUserCoupon(orderInfo.getUserCouponId());
                if (userCoupon != null && userCoupon.getCoupon() != null) {
                    Coupon coupon = userCoupon.getCoupon();
                    if (Global.COUPON_TYPE_FIX_PRICE == coupon.getType()) {
                        //满减
                        return orderInfo.getOrderPrice().subtract(coupon.getCouponPrice());
                    } else if (Global.COUPON_TYPE_RATE == coupon.getType()) {
                        //打折
                        return orderInfo.getOrderPrice().multiply(coupon.getCouponRate());
                    }
                }
            }
        }
        //返回订单总价
        return orderInfo.getOrderPrice();
    }

    public void payFinishOrder(OrderInfo orderInfo) {
        orderInfo.setPayStatus(Global.ORDER_PAY_STATUS_PAID);
        orderInfo.setPayTime(DateUtil.getSysTime());
        updateOrder(orderInfo);
    }

    int updateOrder(OrderInfo order) {
        return orderDao.updateOrderInfo(order);
    }

    private String generateOrderSn() {
        String orderSn = StringUtil.getOrderSn();
        List<String> orderSns = getAllOrderSn();
        while (orderSns.contains(orderSn)) {
            orderSn = StringUtil.getOrderSn();
        }
        return orderSn;
    }

    private List<String> getAllOrderSn() {
        List<String> orderSns = orderDao.getAllOrderSn();
        if (orderSns == null) {
            orderSns = Collections.emptyList();
        }
        return orderSns;
    }

    public int deleteOrder(OrderInfo order) {
        if (StringUtils.isNotBlank(order.getUserCouponId())) {
            int rollBackRows = userCouponService.rollBackUserCoupon(order.getUserCouponId());
            if (rollBackRows == 0) {
                return 0;
            }
        }
        return orderDao.deleteOrderInfo(order.getOrderSn());
    }
}
*/
